import { Button, Form, Input, message } from 'antd'
import React, { useEffect, useState } from 'react'
import './index.css'
import { userLogin } from '@/api/login';
import { useNavigate } from 'react-router-dom';

export default function Login() {
  const [messageApi, contextHolder] = message.useMessage();
  const [loading, setLoading] = useState(false);
  const navigate = useNavigate();

  useEffect(() => {
    if (localStorage.getItem('token')) {
      navigate('/home');
    }
  }, [navigate])

  const onFinish = async (values) => {
    try {
      setLoading(true);
      const params = {
        username: values.username,
        password: values.password
      }
      const res = await userLogin(params)
      if (res.data) {
        localStorage.setItem('token', res.data.token);
        messageApi.open({
          type: 'success',
          content: '登录成功',
        })
        navigate('/home');
      } else {
        messageApi.open({
          type: 'error',
          content: res.message,
        });
      }
      setLoading(false);
    } catch (error) {
      console.log(error)
      setLoading(false);
    }
  };

  return (
    <>
      {contextHolder}
      <div className="login-container">
        <div className="login-form-wrapper">
          <h2 className="login-title">登录</h2>
          <Form
            name="login-form"
            initialValues={{ remember: true }}
            onFinish={onFinish}
            layout="vertical"
          >
            <Form.Item
              label="用户名"
              name="username"
              rules={[{ required: true, message: '请输入用户名' }]}
            >
              <Input />
            </Form.Item>

            <Form.Item
              label="密码"
              name="password"
              rules={[{ required: true, message: '请输入密码' }]}
            >
              <Input.Password />
            </Form.Item>

            <Form.Item>
              <Button
                type="primary"
                htmlType="submit"
                block
                loading={loading}
              >
                登录
              </Button>
            </Form.Item>
          </Form>
        </div>
      </div>
    </>

  )
}
